<template>
  <div class="login">
    <snackbars :value="showbar" :text="text"/>
    <v-form v-model="valid" ref="loginForm">
      <v-text-field label="邮箱" :rules="rulesEmail" v-model="email" />
      <v-text-field
        label="密码"
        type="password"
        :rules="rulesPwd"
        v-model="pwd"
      />
    </v-form>
    <div class="btn">
      <v-btn style="background-image: linear-gradient(-60deg, #16a085 0%, #f4d03f 100%);color: #fff" @click="handleLogin">
        登录
      </v-btn>
      <v-btn style="background-image: linear-gradient(-60deg, #ff5858 0%, #f09819 100%);;color: #fff" @click="handleReset">
        重置
      </v-btn>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Snackbars from '@/components/Snackbars'
import {userLogin,userLoginAns} from '@/api/user'
export default Vue.extend({
  name: "SignIn",
  components: {
    Snackbars
  },
  methods: {
    handleReset(){
      const {loginForm} = this.$refs as any
      loginForm.reset()
    },
    handleLogin(){
      const {loginForm} = this.$refs as any
      loginForm.validate();
      if(this.valid){
        userLogin(this.email,this.pwd)
            .then(res => {
              const {code,msg,token} = res as unknown as userLoginAns
              loginForm.reset()
              if(code === 200){
                this.text = msg + ',即将刷新页面'
              }else{
                this.text = msg
              }
              this.showbar = true
              setTimeout(() => {
                this.showbar = false
                this.text = ''
                if(code === 200){
                localStorage.setItem('token',token)
                this.$store.dispatch('user/getUserInfo')
                this.$router.go(0)
              }
              },2000)
            })
      }
    }
  },
  data: () => ({
    showbar: false,
    text: '',
    valid: false,
    email: '',
    pwd: '',
     rulesEmail: [
      (value: string) => !!value || "邮箱不能为空",
      (value: string) =>
        (value &&
          /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) ||
        "邮箱格式不正确",
    ],
    rulesPwd: [
      (value: string) => !!value || "密码不能为空",
    ]
  })
})
</script>

<style lang='scss'>
.login {
  .btn {
    margin-top: 2vh;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-around;
  }
}
</style>